package web

import (
	"net/http"
)

type MethodRoute map[string]http.Handler

func (route *MethodRoute) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if h, ok := (*route)[r.Method]; ok {
		h.ServeHTTP(w, r)
		return
	}
	HandleMethodNotAllow(r)
}

func (route *MethodRoute) Handle(method string, handler http.Handler) {

	if method == "" {
		panic("http: invalid method")
	}
	if handler == nil {
		panic("http: nil handler")
	}

	if _, exist := (*route)[method]; exist {
		panic("http: multiple registrations for " + method)
	}

	(*route)[method] = handler
}

func (route *MethodRoute) GET(handler http.Handler) *MethodRoute {
	route.Handle(http.MethodGet, handler)
	return route
}
func (route *MethodRoute) POST(handler http.Handler) *MethodRoute {
	route.Handle(http.MethodPost, handler)
	return route
}
func (route *MethodRoute) PUT(handler http.Handler) *MethodRoute {
	route.Handle(http.MethodPut, handler)
	return route
}
func (route *MethodRoute) DELETE(handler http.Handler) *MethodRoute {
	route.Handle(http.MethodDelete, handler)
	return route
}

func (route *MethodRoute) HandleFunc(method string, handler func(w http.ResponseWriter, r *http.Request)) {
	route.Handle(method, http.HandlerFunc(handler))
}
